import { ref, computed } from 'vue'
import { userAPI } from '~/services/api'

// 全局状态变量
const currentUser = ref(null)
const isLoggedIn = ref(false)
const loginTime = ref(null)

// 登录超时时间：30分钟
const LOGIN_TIMEOUT = 30 * 60 * 1000 // 30分钟

// 从localStorage加载登录状态
const loadAuthFromStorage = () => {
  try {
    const storedUser = localStorage.getItem('currentUser')
    const storedLoginTime = localStorage.getItem('loginTime')
    
    if (storedUser && storedLoginTime) {
      const user = JSON.parse(storedUser)
      const loginTimeStamp = parseInt(storedLoginTime)
      const now = Date.now()
      
      // 检查是否超时
      if (now - loginTimeStamp < LOGIN_TIMEOUT) {
        currentUser.value = user
        isLoggedIn.value = true
        loginTime.value = loginTimeStamp
        console.log('✅ 从localStorage恢复登录状态:', user.username)
        return true
      } else {
        // 登录已超时，清除存储
        clearAuth()
        console.log('⏰ 登录状态已超时，已清除')
        return false
      }
    }
  } catch (error) {
    console.error('❌ Failed to load auth from storage:', error)
    clearAuth()
  }
  return false
}

// 保存登录状态到localStorage
const saveAuthToStorage = (user) => {
  try {
    if (!user || typeof user !== 'object') {
      console.error('❌ Invalid user data:', user)
      return
    }
    
    localStorage.setItem('currentUser', JSON.stringify(user))
    localStorage.setItem('loginTime', Date.now().toString())
    currentUser.value = user
    isLoggedIn.value = true
    loginTime.value = Date.now()
    console.log('💾 保存登录状态到localStorage:', user.username || 'unknown')
  } catch (error) {
    console.error('❌ Failed to save auth to storage:', error)
  }
}

// 清除登录状态
const clearAuth = () => {
  localStorage.removeItem('currentUser')
  localStorage.removeItem('loginTime')
  currentUser.value = null
  isLoggedIn.value = false
  loginTime.value = null
  console.log('🗑️ 清除登录状态')
}

// 检查登录状态是否有效
const checkAuthValidity = () => {
  if (!isLoggedIn.value || !loginTime.value) {
    console.log('🔍 检查登录状态: 未登录')
    return false
  }
  
  const now = Date.now()
  if (now - loginTime.value >= LOGIN_TIMEOUT) {
    // 登录已超时
    console.log('⏰ 登录状态已超时')
    clearAuth()
    return false
  }
  
  console.log('✅ 登录状态有效:', currentUser.value?.username)
  return true
}

// 用户登录
const login = async (username, password) => {
  try {
    const userData = await userAPI.login({ username, password })
    console.log('🔍 登录API返回数据:', userData)
    
    if (!userData || typeof userData !== 'object') {
      console.error('❌ Invalid user data from API:', userData)
      return { success: false, error: '服务器返回数据格式错误' }
    }
    
    saveAuthToStorage(userData)
    console.log('🎉 登录成功:', userData.username || 'unknown')
    return { success: true, user: userData }
  } catch (error) {
    console.error('❌ Login failed:', error)
    return { success: false, error: error.message }
  }
}

// 用户退出登录
const logout = async () => {
  console.log('🔄 useAuth: 开始退出登录流程...')
  
  try {
    console.log('📡 useAuth: 调用后端退出接口...')
    await userAPI.logout()
    console.log('✅ useAuth: 后端退出登录成功')
  } catch (error) {
    console.error('❌ useAuth: Logout API failed:', error)
  } finally {
    console.log('🧹 useAuth: 清除本地认证状态...')
    clearAuth()
    console.log('👋 useAuth: 退出登录完成，状态已清除')
  }
}

// 获取剩余登录时间（分钟）
const remainingTime = computed(() => {
  if (!loginTime.value) return 0
  const now = Date.now()
  const remaining = LOGIN_TIMEOUT - (now - loginTime.value)
  return Math.max(0, Math.floor(remaining / 60000)) // 转换为分钟
})

// 初始化时加载登录状态
if (process.client) {
  // 使用 nextTick 确保在 DOM 更新后加载
  import('vue').then(({ nextTick }) => {
    nextTick(() => {
      loadAuthFromStorage()
    })
  })
}

// 登录状态管理
export const useAuth = () => {
  return {
    currentUser,
    isLoggedIn,
    loginTime,
    remainingTime,
    login,
    logout,
    clearAuth,
    checkAuthValidity,
    loadAuthFromStorage
  }
}
